package com.gzw.scm.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v7.widget.Toolbar;
import com.google.gson.reflect.TypeToken;
import com.gzw.scm.MyApplication;
import com.gzw.scm.R;
import com.gzw.scm.adapter.YJCKAdapter;
import com.gzw.scm.base.NewBaseActivity;
import com.gzw.scm.bean.CodeInfo;
import com.gzw.scm.bean.Info;
import com.gzw.scm.utils.BtnUtils;
import com.gzw.scm.utils.HttpUtils;
import com.gzw.scm.utils.JsonUtil;
import com.gzw.scm.utils.SortUtil;
import com.gzw.scm.utils.T;
import com.gzw.scm.utils.UrlUtils;

import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * Created by Administrator on 2018/3/5 0005.
 */

public class YJCKActivity extends NewBaseActivity implements View.OnClickListener {
    private RecyclerView mRvContent;
    private TextView mTvNumber;
    private TextView mTvLabel;
    private TextView mTvOrder;
    private Button mBtnClassifyQuery;
    private Button mBtnClassifyScreen;
    private LinearLayout mConditionQuery;
    private LinearLayout mConditionScreen;
    private Button mBtnQuery;
    private Button mBtnOutbound;
    private Button mBtnClear;
    private YJCKAdapter yjckAdapter;
    private EditText mEtBox;
    private EditText mEtLabel;
    private EditText mEtOrder;
    private Toolbar toolbar;
    private Context mContext;

    private String INTENT_ACTION = "com.symbol.scanconfig.SCANDEMO";
    private String DATA_STRING_TAG = "com.symbol.scanconfig.decode_data";
    private String INTENT_CATEGORY = "com.symbol.category.DEFAULT";

    private boolean ismEtBoxFocus,ismEtLabelFocus;
    private List<Info> ls_info;
    private Logger log;
    private ProgressDialog mProgressDialog;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_yjck);
    }

    @Override
    protected void initViews() {
        mContext=this;
        initView();
    }

    @Override
    protected void initData() {
        ls_info = new ArrayList<>();
        initData1();

    }

    @Override
    protected void initEvents() {
        mTvNumber.setOnClickListener(this);
        mTvLabel.setOnClickListener(this);
        mTvOrder.setOnClickListener(this);

        initButton();

        /**Editview是否获取焦点*/
        mEtBox.setOnFocusChangeListener((v, hasFocus) ->{
            if (hasFocus) {
                // 此处为得到焦点时的处理内容
                ismEtBoxFocus = true;
            } else {
                // 此处为失去焦点时的处理内容
                ismEtBoxFocus = false;
            }
        });

        mEtLabel.setOnFocusChangeListener((v, hasFocus) ->{
            if (hasFocus) {
                // 此处为得到焦点时的处理内容
                ismEtLabelFocus = true;
            } else {
                // 此处为失去焦点时的处理内容
                ismEtLabelFocus = false;
            }
        });
    }

    private void initView() {
        toolbar = (Toolbar)findViewById(R.id.toolbar);
        mRvContent = (RecyclerView) findViewById(R.id.rv_content);
        mTvNumber = (TextView) findViewById(R.id.tv_number);
        mTvLabel = (TextView) findViewById(R.id.tv_label);
        mTvOrder = (TextView) findViewById(R.id.tv_order);
        mBtnClassifyQuery = (Button) findViewById(R.id.btn_classify_query);
        mBtnClassifyScreen = (Button) findViewById(R.id.btn_classify_screen);
        mConditionQuery = (LinearLayout) findViewById(R.id.ll_condition_query);
        mConditionScreen = (LinearLayout) findViewById(R.id.ll_condition_screen);
        mBtnQuery = (Button) findViewById(R.id.btn_query);
        mBtnOutbound = (Button) findViewById(R.id.btn_outbound);
        mBtnClear= (Button) findViewById(R.id.btn_clear);
        mEtBox = (EditText) findViewById(R.id.et_box);
        mEtLabel = (EditText) findViewById(R.id.et_label);
        mEtOrder = (EditText) findViewById(R.id.et_order);
        mBtnOutbound.setEnabled(true);


        mRvContent.setHasFixedSize(true);
        //设置布局管理器
        mRvContent.setLayoutManager(new LinearLayoutManager(this));
        //设置Item增加、移除动画
        mRvContent.setItemAnimator(new DefaultItemAnimator());

        //初始化 log
        log=Logger.getLogger(this.getClass());

    }

    /**按钮点击方法*/
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void initButton() {
        toolbar.setNavigationOnClickListener(v -> finish());

        mBtnClassifyQuery.setSelected(true);
        mBtnClassifyQuery.setOnClickListener(v -> {
                mBtnClassifyQuery.setSelected(true);
                mBtnClassifyScreen.setSelected(false);
                mConditionQuery.setVisibility(View.VISIBLE);
                mConditionScreen.setVisibility(View.GONE);
                mBtnQuery.setText("查询");
                ismEtLabelFocus=false;
        });

        mBtnClassifyScreen.setOnClickListener(v -> {
                mBtnClassifyScreen.setSelected(true);
                mBtnClassifyQuery.setSelected(false);
                mConditionQuery.setVisibility(View.GONE);
                mConditionScreen.setVisibility(View.VISIBLE);
                mBtnQuery.setText("筛选");
                ismEtBoxFocus=false;
        });

        mBtnQuery.setOnClickListener(v -> {
                if (mBtnClassifyQuery.isSelected()) {
                    if(null==mEtBox.getText()||"".equals(mEtBox.getText())){
                        T.showShort(mContext, "请先输入查询条件");
                    }else{
                      scrollToPosition(); //查询，滚动到查询数据位置
                    }
                } else if (mBtnClassifyScreen.isSelected()) {
                    if(null==mEtLabel.getText()&&null==mEtOrder.getText()){
                        T.showShort(mContext, "请先输入查询条件");
                    }else{
                        screenData(); //筛选出需要的数据
                    }
                }
        });

        mBtnClear.setOnClickListener(v ->{
            if (mBtnClassifyQuery.isSelected()) {
                if(null==mEtBox.getText()||"".equals(mEtBox.getText())){
                }else{
                    mEtBox.setText("");
                    mRvContent.smoothScrollToPosition(0);
                }
            } else if (mBtnClassifyScreen.isSelected()) {
                if(null==mEtLabel.getText()&&null==mEtOrder.getText()){
                }else{
                    mEtLabel.setText("");
                    mEtOrder.setText("");

                    yjckAdapter = new YJCKAdapter(mContext,ls_info);
                    mRvContent.setAdapter(yjckAdapter);
                }
            }
        });


        mBtnOutbound.setOnClickListener(v -> {
            if(BtnUtils.isFastClick()){
            mBtnOutbound.setClickable(false);

            List<Info> list = yjckAdapter.getCheckedList();

                if(list.size()==0){
                    T.showShort(mContext,"请先选择要出库的周转箱");
                    mBtnOutbound.setClickable(true);
                    return;
                }

                //订单号去重
                HashSet<String> hashSet = new HashSet<>();
                for (int i = 0; i < list.size(); i++) {
                    hashSet.add(list.get(i).getWordernumber());
                }
                //周转箱编号去重
                HashSet<String> hashSet1 = new HashSet<>();
                for (int i = 0; i < list.size(); i++) {
                    hashSet1.add(list.get(i).getTboxno());
                }

                //查询未绑定供应商的信息
                HashSet<String> hashSet2 = new HashSet<>();
                for (int i = 0; i < list.size(); i++) {
                    if(isNull(list.get(i).getSuppname())){
                     hashSet2.add(list.get(i).getTboxno());
                    }
                }

            showConfirmDialog(hashSet1.size(), hashSet.size(),hashSet2.size());
            }
        });
    }

    /**筛选数据*/
    private void screenData() {
        ArrayList<Info> list = new ArrayList<>();
        List<Info> infoList = yjckAdapter.getList();
        String label = mEtLabel.getText().toString();
        String order = mEtOrder.getText().toString();
        if (!label.equals("") && order.equals("")) {
            for (Info info : infoList) {
                if (info.getOrdnoid1().equals(label))
                    list.add(info);
            }
        } else if (label.equals("") && !order.equals("")) {
            for (Info info : infoList) {
                if (info.getWordernumber().equals(order))
                    list.add(info);
            }
        } else {
            for (Info info : infoList) {
                if (info.getOrdnoid1().equals(label) && info.getWordernumber().equals(order))
                    list.add(info);
            }
        }
        YJCKAdapter screenAdapter = new YJCKAdapter(this, list);
        mRvContent.swapAdapter(screenAdapter, false);
    }

    private void scrollToPosition() {
        int position = yjckAdapter.getPosition(mEtBox.getText().toString());
        mRvContent.smoothScrollToPosition(position);
    }

    /**上传数据的提示框*/
    private void showConfirmDialog(int box, int order, int unBind) {
        mBtnOutbound.setClickable(true);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setNegativeButton("取消", (dialog, which) -> {
            mBtnOutbound.setClickable(true);

        }).setPositiveButton("确定", (dialog, which) -> {
                //TODO("not implemented") 1、发送请求 2、完成网络请求后清除出库箱子，清空查询条件
                sendData();
                mBtnOutbound.setClickable(true);

        });
        String msg ="本次出库" + box + "个周转箱，" + order + "个订单，是否出库";
        if(unBind>0){
            msg ="本次出库" + box + "个周转箱，" + order + "个订单，"+unBind+"个周转箱" +
                    "未绑定供应商，是否出库";
        }
        builder.setCancelable(false);
        builder.setMessage(msg)
                .create()
                .show();
    }

    /**查询一键出库信息的数据请求*/
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void initData1() {
        toolbar.setTitle("周转箱出库");
        //http://192.168.5.242:5410/Ntboxs/rdcpp.do?method=PreQuery&&Did=90
        String url = UrlUtils.getInstance().getNewJavaUrl("rdcpp.do", "PreQuery")+"&did="+ MyApplication.getUserInfo().getDid();

        mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
        mProgressDialog.setCancelable(false);
        HttpUtils.doGetAsyn(url,result ->  {
            try {
                //TODO 1、请求服务器获取数据 2、添加数据到adapter
                //{"Data":[{"a":"","aid":0,"aname":"","bdstate":0,"belong":"","belong_name":"","belongid":0,"boxnumber":"","cid":0,"cityname":"","cname":"","cont":"","createtime":"","department_name":"沈阳DC","did":0,"dname":"","end":0,"id":0,"minaddid":0,"nowdid":"90","nowtime":"","nowtime2":"","num":0,"ordnoid":0,"ordnoid1":"P0010007012","peoid":"","pid":0,"pname":"","pointname":"","pointsid":"","rdcid":0,"rdcname":"","state":0,"suppname":"","tbhid":0,"tboxid":32358,"tboxno":"2018030300000001","tboxstate":"","tboxsum":"","thstate":0,"tid":0,"trid":"7264","tsid":"","tsuid":"","uno":"","wcusname":"","whetherdis":"","wordernumber":"1916085605","zid":0,"zname":""}]}
                if (result == null || result.length() == 0) {
                    mHandler.sendEmptyMessage(3);
                    return;
                }
                if(result.contains("Data")){
                    String info = JsonUtil.getMsg(result,"Data").toString();
                    ls_info = JsonUtil.getPersons(info, new TypeToken<List<Info>>() {
                    }.getType());
                    mHandler.sendEmptyMessage(0);
                }
                if(result.contains("系统异常")){
                    mHandler.sendEmptyMessage(5);

                }
            }catch (Exception e) {
                log.info("PreQuery:"+e.toString()+"/result="+result);
                e.printStackTrace();
                showAlertDialog(e.toString());
            }
        });
    }

    /**处理返回值*/
    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    mProgressDialog.dismiss();
                    if(ls_info.size()==0){
                        showAlertDialog("暂无信息");
                    }
                    yjckAdapter = new YJCKAdapter(mContext,ls_info);
                    mRvContent.setAdapter(yjckAdapter);
                    break;
                case 1:
                    mProgressDialog.dismiss();
                    ArrayList<Info> allinfo = (ArrayList<Info>) yjckAdapter.getCheckedList();

                    ArrayList<Info> ls_unBind = new ArrayList<>();
                    for (Info info:allinfo){
                        if(isNull(info.getSuppname())){
                            ls_unBind.add(info);
                        }
                    }
                    allinfo.removeAll(ls_unBind);

                    HashSet<String> hashSet1 = new HashSet<>();
                    for (int i = 0; i < allinfo.size(); i++) {
                        hashSet1.add(allinfo.get(i).getTboxno());
                    }
                    String message = "一键出库成功"+hashSet1.size()+"个周转箱";
                    if(ls_unBind.size()>0){
                           message = "一键出库成功"+hashSet1.size()+"个周转箱,"+ls_unBind.size()
                                +"个周转箱未绑定供应商";
                    }
                    showAlertDialog(message);
                    mEtBox.setText("");
                    mEtLabel.setText("");
                    mEtOrder.setText("");

                    ls_info.removeAll(allinfo);
                    for (int j=0;j<ls_info.size();j++){
                         if(hashSet1.contains(ls_info.get(j).getTboxno())){
                             ls_info.remove(j);
                         }
                    }
                    yjckAdapter = new YJCKAdapter(mContext,ls_info);
                    mRvContent.setAdapter(yjckAdapter);
                    break;
                case 2:
                    mProgressDialog.dismiss();
                    showAlertDialog("一键出库失败");
                    break;
                case 3:
                    mProgressDialog.dismiss();
                    showAlertDialog("连接异常");
                    break;
                case 4:
                    mProgressDialog.dismiss();
                    initData1();
                    showAlertDialog("周转箱已出库");
                    break;
                case 5:
                    mProgressDialog.dismiss();
                    initData1();
                    showAlertDialog("网络异常");
                    break;
                default:
                    break;
            }
        }

    };

    @Override
    public void onClick(View view) {
        List<Info> infoList = yjckAdapter.getList();
        List<Info> list = null;
        switch ((view.getId())) {
            case R.id.tv_number:
                //按周转箱编号排序
                list = SortUtil.numberSort(infoList);
                yjckAdapter.clear();
                break;
            case R.id.tv_label:
                //按箱标签号排序
                list = SortUtil.labelSort(infoList);
                yjckAdapter.clear();
                break;
            case R.id.tv_order:
                //按订单号排序
                list = SortUtil.orderSort(infoList);
                yjckAdapter.clear();
                break;
            case R.id.tv_supplier:
                //按供应商排序
                list = SortUtil.supplierSort(infoList);
                yjckAdapter.clear();
                break;
        }
        if (list != null) {
            for (Info info : list) {
                yjckAdapter.add(info);
            }
        }
    }

    /**
     * 发送信息的数据请求
     * */
    private void sendData(){

        ArrayList<Info> allinfo = (ArrayList<Info>) yjckAdapter.getCheckedList();
        ArrayList<Info> ls_unBind = new ArrayList<>();
        for (Info info:allinfo){
            if(isNull(info.getSuppname())){
                ls_unBind.add(info);
            }
        }
        allinfo.removeAll(ls_unBind);
        if(allinfo.size()==0){
            showAlertDialog("周转箱未绑定供应商不能出库");
            return;
        }

        for  (int i=0;i<allinfo.size()-1;i ++)  {
            for(int j = allinfo.size()- 1;j > i;j--){
                if(allinfo.get(j).getTboxno().equals(allinfo.get(i).getTboxno())){
                    allinfo.remove(j);
                }
            }
        }

        ArrayList<Info> ls_info = new ArrayList<>();
        ls_info.addAll(allinfo);

        for(Info info:ls_info){
           info.setDid(MyApplication.getUserInfo().getDid());
           info.setBelong(String.valueOf(MyApplication.getUserInfo().getBelongId()));
           info.setPeoid(String.valueOf(MyApplication.getUserInfo().getId()));
        }


        String json = JsonUtil.toJson(ls_info);

        String params ="chuku="+json;
        String url=UrlUtils.getInstance().getNewJavaUrl("rdcpp.do", "chuku");

        final String[] result1 = new String[1];
        try {
            mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
            mProgressDialog.setCancelable(false);
            HttpUtils.doPostAsyn(url,params,result ->{
                       result1[0] = result;
                         //ware:1 成功 0 失败
                 mBtnOutbound.setClickable(true);
                        if (result == null || result.length() == 0) {
                            mHandler.sendEmptyMessage(3);
                            return;
                        }
                        if(result.contains("ware")){
                            String info = JsonUtil.getMsg(result,"ware").toString();
                            if(info.equals("1")){
                                mHandler.sendEmptyMessage(1);
                            }

                            if(info.equals("0")){
                                mHandler.sendEmptyMessage(2);
                            }
                            if(info.equals("-1")){
                                mHandler.sendEmptyMessage(4);
                            }
                        }
                if(result.contains("系统异常")){
                    mHandler.sendEmptyMessage(5);

                }

                });
        } catch (Exception e) {
            log.info("chuku:"+e.toString()+"/result="+result1[0]);
            e.printStackTrace();
            showAlertDialog(e.toString());
        }
    }

    /**
     * 注册广播，实现扫描
     * */
    protected void onResume() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(INTENT_ACTION);
        filter.addCategory(INTENT_CATEGORY);
        registerReceiver(receiver, filter);
        super.onResume();
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(INTENT_ACTION)) {
                String data = intent.getStringExtra(DATA_STRING_TAG);
                scanRelust(data);
            }
        }
    };

    protected void onPause() {
        unregisterReceiver(receiver);
        super.onPause();
    }

    /**
     * 判断扫描类型
     * */
    protected String scanRelust(String relust){
      if(ismEtBoxFocus){
          if(relust.contains("SSID")){
              CodeInfo codeInfo = JsonUtil.getPerson(relust, CodeInfo.class);
              String code = codeInfo.getNO();
              mEtBox.setText(code);
          }else{
              Toast.makeText(YJCKActivity.this, "该二维码不是周转箱", Toast.LENGTH_SHORT).show();
          }
      }

      if(ismEtLabelFocus){
          if(relust.substring(0,1).equals("P")&&relust.length()==11){
              mEtLabel.setText(relust);
          }else{
              Toast.makeText(YJCKActivity.this, "该一维码不符合规则", Toast.LENGTH_SHORT).show();
          }
      }
      return relust;
    }


}
